import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Form, Input, Button, Checkbox, Card, message, Typography } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import { postAdminLogin } from '../../api/auth';
const { Title } = Typography;

// 后台管理系统登录页面
const AdminLogin = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);

  const { runAsync: loginRequest } = useRequest(postAdminLogin, {
      manual: true,
    });

  // 处理表单提交
  const onFinish = async (values) => {
    setLoading(true);
    setTimeout(async () => {
      try {
        const res = await loginRequest(values);
        const userInfo = {
          ...res
        };
        localStorage.setItem('adminUser', JSON.stringify(userInfo));
        message.success('登录成功');

        // 跳转到后台首页
        navigate('/admin/dashboard', { replace: true });
      } catch (err) {
        message.error('用户名或密码错误');
      }
      setLoading(false);
    }, 1000);
  };

  return (
    <div className="login-container">
      <Card className="login-form" bordered={false}>
        <div className="text-center mb-20">
          <Title level={2}>商城管理系统</Title>
          <p>管理员登录</p>
        </div>

        <Form
          name="admin_login"
          initialValues={{ remember: true }}
          onFinish={onFinish}
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input
              prefix={<UserOutlined className="site-form-item-icon" />}
              placeholder="用户名"
              size="large"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input
              prefix={<LockOutlined className="site-form-item-icon" />}
              type="password"
              placeholder="密码"
              size="large"
            />
          </Form.Item>

          <Form.Item>
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox>记住我</Checkbox>
            </Form.Item>

            <a className="login-form-forgot" href="#!" style={{ float: 'right' }}>
              忘记密码
            </a>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              className="login-form-button"
              loading={loading}
              block
              size="large"
            >
              登录
            </Button>
          </Form.Item>
        </Form>

        <div className="text-center">
          <Button type="link" onClick={() => navigate('/home')}>
            返回前台首页
          </Button>
        </div>
      </Card>
    </div>
  );
};

export default AdminLogin; 